﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace AspNetId4Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PhoneCodeLoginController : ControllerBase
    {
        private readonly PhoneCodeService _phoneCodeService;
        private readonly ILogger _logger;

        public PhoneCodeLoginController(
            PhoneCodeService phoneCodeService,
            ILogger<PhoneCodeLoginController> logger)
        {
            _phoneCodeService = phoneCodeService;
            _logger = logger;
        }

        /// <summary>
        /// 发送验证码到手机号
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        [ProducesResponseType(StatusCodes.Status200OK)]
        [AllowAnonymous]
        [HttpGet("SendPhoneCode")]
        public async Task<string> SendPhoneCode(string phoneNumber)
        {
            //根据手机号获取用户信息
            var result = await _phoneCodeService.SendPhoneCode(phoneNumber);

            return result.Msg;
        }

        #region 废弃
#if false
        /// <summary>
        /// 发送验证码到手机号
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        [ProducesResponseType(StatusCodes.Status200OK)]
        [AllowAnonymous]
        [HttpGet("SendPhoneCode")]
        public async Task<string> SendPhoneCode(string phoneNumber)
        {
            //根据手机号获取用户信息
            var appUser = await GetUserByPhoneNumberAsync(phoneNumber);
            if (appUser == null)
            {
                return "手机号无效";
            }

            //发送验证码到手机号，需要调用短信服务平台Web Api，这里模拟发送
            string verificationCode = (new Random()).Next(1000, 9999).ToString();

            //验证码缓存10分钟
            _memoryCache.Set(phoneNumber, verificationCode, TimeSpan.FromMinutes(10));

            _logger.LogInformation($"发送验证码{verificationCode}到手机号{phoneNumber}, 有效期{DateTime.Now.AddMinutes(10)}");

            return "发送验证码成功";
        }

        //根据手机号获取用户信息
        private async Task<ApplicationUser> GetUserByPhoneNumberAsync(string phoneNumber)
        {
            var appUser = await _context.Users.AsNoTracking()
                .FirstOrDefaultAsync(x => x.PhoneNumber == phoneNumber);

            return appUser;
        }
#endif
        #endregion
    }
}
